﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Data.Storage;
using Umbraco.Forms.Core;
using System.Xml.XPath;
using System.Xml;
using umbraco;

namespace ContourStrikesAgain
{
    [XsltExtension]
    public class XsltExtensions
    {
        public static XPathNodeIterator PossibleAnswers(string guid)
        {
            FormStorage fs = new FormStorage();

            Form f = fs.GetForm(new Guid(guid));
            fs.Dispose();

            XmlDocument d = new XmlDocument();
            XmlNode root = d.CreateElement("questions");

            foreach (Field fld in f.AllFields)
            {

                if (fld.FieldType.SupportsPrevalues
                    && fld.PreValueSource.Type.GetPreValues(fld).Count > 0)
                {
                    XmlNode question = d.CreateElement("question");
                    XmlNode caption = d.CreateElement("caption");

                    XmlCDataSection questionvalue = d.CreateCDataSection(fld.Caption);
                    caption.AppendChild(questionvalue);

                    question.AppendChild(caption);

                    XmlNode answers = d.CreateElement("answers");

                    foreach (PreValue pv in fld.PreValueSource.Type.GetPreValues(fld))
                    {
                        XmlNode answer = d.CreateElement("answer");
                        XmlAttribute answerId = d.CreateAttribute("id");
                        answerId.Value = pv.Id.ToString();
                        answer.Attributes.Append(answerId);
                        XmlCDataSection value = d.CreateCDataSection(pv.Value);
                        answer.AppendChild(value);
                        answers.AppendChild(answer);
                    }

                    question.AppendChild(answers);
                    root.AppendChild(question);
                }

            }

            d.AppendChild(root);

            return d.CreateNavigator().Select(".");
        }
    }
}